/**
 * 主路由文件
 *
 * @author  bian
 * @createDate 2016.10.1
 */

// library module
const Router = require("koa-router")
const fs = require("fs")
const path = require("path")

// my module
let logger = require("../instances/logger")
const Task = require("../task/index")

// code
let router = new Router()

/**
 * error process
 */
router.use(function *(next){
    try{
        let ctx = this
        ctx.task = new Task(ctx)
        yield next
    }catch (err){
        if(err.errno === "EPIPE" || err.errno === "ECONNRESET"){
            return
        }
        if(err.message == "参数错误"){
            return
        }
        logger.error(err)
    }
})

let loadDir = (dir) => {
    fs
        .readdirSync(dir)
        .forEach( (file) => {
            let nextPath = path.join(dir, file)
            let stat = fs.statSync(nextPath)
            if (stat.isDirectory()) {
                loadDir(nextPath)
            } else if (stat.isFile() && file.indexOf(".") !== 0 && file !== "index.js") {
                require(nextPath)(router)
            }
        })
}

loadDir(__dirname)

module.exports = () => router.routes()